<?php
class Article extends DataObject{
    private static $db = array(
        'Title'     => 'Varchar(255)',
        'UrlSegment' => 'Varchar(255)',
        'Content'   => 'HTMLText',
        'Summary'   => 'Text',
        'Tags'      => 'Text',
        'Date'      => 'SS_Datetime',
        'View'      => 'Int',
        'Featured' => 'Boolean',
        'Publish'   => 'Boolean',
        'SortOrder' => 'Int'
    );

    private static $has_one = array(
        'Image' => 'Image'
    );

    private static $has_many = array(

    );

    private static $many_many = array(
        'ArticleCategories' => 'ArticleCategory'
    );

    static $default_sort = 'SortOrder';
    static $defaults = array('View' => 0, 'Publish' => true);

    public function getCMSFields(){
        $fields = parent::getCMSFields();

        $fields->removeByName('ArticleCategories');

        $fields->addFieldToTab('Root.Main', new TextField('Title', 'Title'), "Content");
        $fields->addFieldToTab('Root.Main', new TextField('UrlSegment', 'Url Segment'), "Content");

        $fields->addFieldToTab("Root.Main", $dateField = new DatetimeField("Date", "Date", date("Y-m-d H:i:s")),"Content");
        $dateField->getDateField()->setConfig('showcalendar', true);
        $dateField->getTimeField()->setConfig('timeformat', 'H:m:s');

        $fields->addFieldToTab("Root.Main", new TextField("Tags", "Tags (comma sep.)"),"Content");


        $categories = ArticleCategory::get()->map('ID', 'Title')->toArray();
        asort($categories);
        $categoryField = new ListboxField('ArticleCategories', 'Add Category', $categories);
        $categoryField->setMultiple(true);

        $fields->addFieldToTab('Root.Main', $categoryField, 'Content');

        $fields->addFieldToTab('Root.Main', new CheckboxField('Featured', 'Featured'), "Content");

        $fields->addFieldToTab("Root.Main", new ReadonlyField('View', 'View'), "Content");
        $fields->addFieldToTab('Root.Main', new UploadField('Image', 'Image'), "Content");
        $fields->addFieldToTab('Root.Main', $summaryF = new TextareaField('Summary', 'Summary'), 'Content');
        $summaryF->setRows(3);

        $fields->addFieldToTab("Root.Main", new HiddenField('SortOrder'));

        $this->extend('updateCMSFields', $fields);

        return $fields;
    }

    function onBeforeWrite() {
        parent::onBeforeWrite();

        if($this->Title == null || $this->Title == ''){
            $this->Title  = 'product-'.$this->ID;
        }

        if ($this->ID == 0) {
            $this->CreatedDate = date('Y-m-d H:i:s');
            $this->UpdateDate  = date('Y-m-d H:i:s');
        }else{
            $this->UpdateDate  = date('Y-m-d H:i:s');
        }

        if($this->UrlSegment == null || $this->UrlSegment == ''){
            $this->UrlSegment = $this->checkUniqueUrlSegment(SiteTree::create()->generateURLSegment($this->Title));
        }else{
            $this->UrlSegment = $this->checkUniqueUrlSegment(SiteTree::create()->generateURLSegment($this->UrlSegment));
        }

    }

    function checkUniqueUrlSegment($url_segment){

        $articles = Article::get()->filter(array('UrlSegment' => $url_segment));

        $num = time();

        if($articles->Count() > 0){
            if($articles->Count() == 1){
                $article = $articles->first();
                if( $article->ID == $this->ID ){
                    return $url_segment;
                }else{
                    return $url_segment . '-' . $num;
                }
            }else{
                return $url_segment . '-' . $num;
            }
        }
        return $url_segment;

    }

    public function SummaryFields(){
        return array(
            'Title'            => 'Title',
            'Date'             => 'Date',
            'summary_category' => 'Category'
        );
    }

    function summary_category(){
        $categories = $this->ArticleCategories()->map('Title')->toArray();
        return implode(', ', $categories);
    }

    /**
     * Safely split and parse all distinct tags assigned to this BlogEntry
     *
     * @return array Associative array of lowercase tag to native case tags
     */
    public function TagNames() {
        $tags = preg_split("/\s*,\s*/", trim($this->Tags));
        $results = array();
        foreach($tags as $tag) {
            if($tag) $results[mb_strtolower($tag)] = $tag;
        }
        return $results;
    }

    /**
     * Returns the tags added to this blog entry
     *
     * @return ArrayList List of ArrayData with Tag, Link, and URLTag keys
     */
    public function TagsCollection() {

        $tags = $this->TagNames();
        $output = new ArrayList();

        $link = ($parent = $this->getParent()) ? $parent->Link('tag') : '';
        foreach($tags as $tag => $tagLabel) {
            $urlKey = urlencode($tag);
            $output->push(new ArrayData(array(
                'Tag' => $tagLabel,
                'Link' => Controller::join_links($link, $urlKey),
                'URLTag' => $urlKey
            )));
        }

        return $output;
    }
}